//
//  NaviManager.m
//  DlCordova
//
//  Created by 吴Sir on 16-4-26.
//
//

#import "NaviManager.h"
#import "NSDictionary+CordovaPreferences.h"

@implementation NaviManager

- (void) action:(CDVViewController *) vc url:(NSString *) url
{
    NSLog(@"navi url %@", url);
    if (url && url.length>5)
    {
        url = [url substringFromIndex:5];// 取掉navi:头
        if ([url isEqualToString:@"back"]) // 返回上一页
        {
            NSLog(@"%@ ", url);
            [self back:vc num:1];
        }
        else if ([url rangeOfString:@"back?"].location == 0) // 返回上N页
        {
            NSLog(@"%@ ", url);
            int n = [[url substringFromIndex:5] intValue];
            if (n > 0) {
                [self back:vc num:n];
            }
        }
        else if ([url rangeOfString:@"home"].location == 0) // 返回到主界面
        {
            NSLog(@"%@ ", url);
            int n = 0;
            [self home:vc num:n];
        }
        else    // go 进入下一页面
        {
            [self go:vc url:url];
        }
    }
}

- (id)newCordovaViewWithFrame:(CGRect)bounds vc:(CDVViewController*) vc url:(NSURL *) url
{
    NSString* defaultWebViewEngineClass = @"CDVUIWebViewEngine";
    NSDictionary *settings = vc.settings;
    NSString* webViewEngineClass = [settings cordovaSettingForKey:@"CordovaWebViewEngine"];
    
    if (!webViewEngineClass) {
        webViewEngineClass = defaultWebViewEngineClass;
    }
    
    // Find webViewEngine
    id <CDVWebViewEngineProtocol> webViewEngine;
    if (NSClassFromString(webViewEngineClass)) {
        webViewEngine = [[NSClassFromString(webViewEngineClass) alloc] initWithFrame:bounds];
        // if a webView engine returns nil (not supported by the current iOS version) or doesn't conform to the protocol, or can't load the request, we use UIWebView
        if (!webViewEngine || ![webViewEngine conformsToProtocol:@protocol(CDVWebViewEngineProtocol)] || ![webViewEngine canLoadRequest:[NSURLRequest requestWithURL:url]]) {
            webViewEngine = [[NSClassFromString(defaultWebViewEngineClass) alloc] initWithFrame:bounds];
        }
    } else {
        webViewEngine = [[NSClassFromString(defaultWebViewEngineClass) alloc] initWithFrame:bounds];
    }
    
    if ([webViewEngine isKindOfClass:[CDVPlugin class]]) {
        int tag = [[NSDate date] timeIntervalSince1970];
        [webViewEngine.engineWebView setTag:tag];
        [vc registerPlugin:(CDVPlugin*)webViewEngine withClassName:[NSString stringWithFormat:@"%@_%d", webViewEngineClass, tag]];
    }
    
    return webViewEngine;
}

- (void) go:(CDVViewController *) vc url:(NSString *) url
{
    UIView *outView = [[vc.view subviews] lastObject];
    
    NSURL *URL = [NSURL fileURLWithPath:[vc.commandDelegate pathForResource:url]];
    NSLog(@"go %@", URL);
    CGRect webViewBounds = vc.view.bounds;
    webViewBounds.origin = vc.view.bounds.origin;
    int width = webViewBounds.size.width;
    int height = webViewBounds.size.height;
    
    id <CDVWebViewEngineProtocol> webViewEngine = [self newCordovaViewWithFrame:webViewBounds vc:vc url:URL];
    
    webViewEngine.engineWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [vc.view addSubview:webViewEngine.engineWebView];
//    [vc.view sendSubviewToBack:webViewEngine.engineWebView];
    NSLog(@"subviews %@ ", [vc.view subviews]);
    UIView *inView = webViewEngine.engineWebView;
    vc.webViewEngineTag = (int)[inView tag];
    
//    [CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
//        _userAgentLockToken = lockToken;
//        [CDVUserAgentUtil setUserAgent:vc.userAgent lockToken:lockToken];
        if (URL) {
            NSURLRequest* appReq = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
            [webViewEngine loadRequest:appReq];
        } else {
            NSString* loadErr = [NSString stringWithFormat:@"ERROR: Start Page at '%@' was not found.", url];
            NSLog(@"%@", loadErr);
            
            NSURL* errorUrl = [vc errorURL];
            if (errorUrl) {
                errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [loadErr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] relativeToURL:errorUrl];
                NSLog(@"%@", [errorUrl absoluteString]);
                [webViewEngine loadRequest:[NSURLRequest requestWithURL:errorUrl]];
            } else {
                NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>", loadErr];
                [webViewEngine loadHTMLString:html baseURL:nil];
            }
        }
//    }];
    
    inView.frame = CGRectMake(width, 0, width, height);
    [UIView animateWithDuration:0.5
                          delay: 0.0
                        options: UIViewAnimationOptionCurveLinear
                     animations:^{
                         // 以iPhone 6s 750x1334
                         float scale = [UIScreen mainScreen].applicationFrame.size.width/750;
                         // 当前页面动画
                         CGRect originFrame = outView.frame;
                         originFrame.origin.x = originFrame.origin.x-220*scale;
                         outView.frame = originFrame;
                         // 新页面动画
                         inView.frame = CGRectMake(0, 0, width, height);
                     }
                     completion:nil
     ];
}

- (void) back:(CDVViewController *) vc num:(int) n
{
    NSArray *subviews = [vc.view subviews];
    int subviesCount = (int)[subviews count];
    if (n >= subviesCount) {
        n = subviesCount-1;
    }
    // 最后一个页面
    UIWebView *lastView = [subviews lastObject];
    
    // 即将还原界面
    UIView *restoreView = [subviews objectAtIndex:(subviesCount-(n+1))];
    
    if (n > 1) {
        for (int i=(subviesCount-2); i>(subviesCount-(n+1)); i--) {
            [[subviews objectAtIndex:i] removeFromSuperview];
        }
    }
    
    // 退场动画
    [UIView animateWithDuration:0.5
                          delay: 0.0
                        options: UIViewAnimationOptionCurveLinear
                     animations:^{
                         // 以iPhone 6s 750x1334
                         float scale = [UIScreen mainScreen].applicationFrame.size.width/750;
                         // 进入的View
                         CGRect inFrame = restoreView.frame;
                         inFrame.origin.x = inFrame.origin.x+220*scale;
                         restoreView.frame = inFrame;
                         // 退出的View
                         lastView.frame = CGRectMake(lastView.frame.size.width, lastView.frame.origin.y, lastView.frame.size.width, lastView.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         [lastView removeFromSuperview];
                         int tag = (int)[lastView tag];
                         [vc.pluginObjects removeObjectForKey:[NSString stringWithFormat:@"CDVUIWebViewEngine_%d", tag]];
                         vc.webViewEngineTag = (int)[restoreView tag];
                     }
     ];
}

- (void) home:(CDVViewController *) vc num:(int) n
{
    NSArray *subviews = [vc.view subviews];
    int subviesCount = (int)[subviews count];
    [self back:vc num:subviesCount-1];
}


@end

